<template>
  <Main class="page-wrapper">
    <div slot="tabbar" class="variables-wrapper">
      <van-tabbar fixed>
        <van-tabbar-item v-for="(item, index) in tabbars" :name="item.name" :icon="item.icon" :key="index" @click="handleTabClick(item)">
          {{ item.title }}
        </van-tabbar-item>
      </van-tabbar>
    </div>
    <van-nav-bar
      title="Catalogue"
      left-arrow
      fixed
      placeholder
      @click-left="onClickLeft"
      class="variables-header-wrapper"
    />
    <BookName :text="bookName" />
    <van-list v-model="loading" :finished="finished" offset="100" finished-text="没有更多了" @load="fetchChapterList">
      <div class="catalogue-list">
        <div class="catalogue-item" v-for="catalogue in catalogueList" :key="catalogue.id" @click="gotoRead(catalogue)">
          <div class="catalogue-name primary-color">
            <span>{{ catalogue.name }}</span>
            <!-- <span>第{{ catalogue }}章</span>
            <span class="space"></span>
            <span>鱼箱</span> -->
          </div>
          <!-- <div class="update-time">2020-04-15</div> -->
          <div class="update-time help-color">{{ catalogue.updatetime | parseTime }}</div>
        </div>
      </div>
    </van-list>
  </Main>
</template>

<script>
import Main from '@/views/layouts/index.vue'
import BookName from '@/components/book-name.vue'
import { getChapterList } from '@/api'
import { List } from 'vant'
import { parseTime } from '@/utils'

export default {
  components: {
    Main,
    BookName,
    [List.name]: List
  },

  computed: {
    bookId() {
      return this.$route.query ? this.$route.query.id : ''
    },
    bookName() {
      return this.$route.query ? this.$route.query.bookName : 'Convenient Marriage'
    }
  },

  filters: {
    parseTime(val) {
      return val ? parseTime(val) : '-'
    }
  },

  data() {
    return {
      currentPage: 1,
      loading: false,
      finished: false,
      total: 0,
      oldBookId: '',
      catalogueList: [],
      currentTab: '',
      sort: 'ASC',
      tabbars: [
        {
          title: 'Back',
          name: 'Back',
          icon: 'arrow-left'
        },
        {
          title: 'Asc',
          name: 'Asc',
          icon: 'arrow-up'
        }
      ]
    }
  },

  activated() {
    if (this.oldBookId && this.bookId) {
      if (this.oldBookId !== this.bookId) {
        this.finished = false
        this.currentPage = 1
        this.total = 0
        this.catalogueList = []
        this.fetchChapterList()
        this.$nextTick(() => {
          setTimeout(() => {
            document.querySelector('#app').scrollTop = 0
          }, 50)
        })
      }
    }
    this.oldBookId = this.bookId
  },

  methods: {
    handleTabClick(val) {
      const { name } = val
      if (name === 'Back') {
        this.onClickLeft()
      } else if (name === 'Asc' || name === 'Desc') {
        this.onSort(name)
      }
      console.log(val)
    },
    onSort(name) {
      console.log('on click sort')
      console.log(name)
      this.sort = name.toUpperCase() === 'ASC' ? 'DESC' : 'ASC'
      const tabs = [this.tabbars[0]]
      if (name === 'Asc') {
        tabs.push({
          title: 'Desc',
          name: 'Desc',
          icon: 'arrow-down'
        })
      } else {
        tabs.push({
          title: 'Asc',
          name: 'Asc',
          icon: 'arrow-up'
        })
      }
      this.tabbars = tabs
      this.finished = false
      this.catalogueList = []
      this.currentPage = 1
      this.fetchChapterList()
    },
    onClickLeft() {
      this.$router.go(-1)
    },
    gotoRead(item) {
      const { sortid } = item
      this.$router.push({
        name: 'Read',
        query: {
          id: sortid
        }
      })
    },
    fetchChapterList() {
      this.loading = true
      // 如果第一次请求不能铺满的话，会导致重复请求
      console.log(this.sort)
      getChapterList({
        pagerow: 30,
        page: this.currentPage++,
        bookid: Number(this.bookId),
        sort: this.sort || 'ASC'
        // bookid: 288
      }).then(res => {
        console.log(res)
        const { data, rowcount } = res
        if (data && rowcount) {
          this.total = rowcount
          this.catalogueList.push(...data)
          if (this.catalogueList.length >= this.total) {
            this.finished = true
          }
        } else {
          this.finished = true
        }
      }).finally(() => {
        // 加个定时器处理莫名其妙的重复请求bug（根本原因是获取的数据不够多，或者不够满屏）
        setTimeout(() => {
          this.loading = false
        }, 1500)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import 'assets/css/mixin.scss';

.page-wrapper {
  background-color: #fff;
}

.catalogue-list {
  padding: 0 20px;

  .catalogue-item {
    padding: 10px 0;
    @include border(bottom, #bbb);

    &:last-child {
      @include border(top, transparent);
    }

    .catalogue-name {
      font-size: 16px;
      // color: #373737;
      margin-bottom: 10px;
      line-height: 1.5;
      .space {
        margin: 0 5px;
      }
    }
    .update-time {
      font-size: 14px;
      // color: #848484;
    }
  }
}
</style>
